package com.vivachek.protocol

import com.vivachek.protocol.enums.UnitEnums
import com.vivachek.protocol.exception.CRCException
import com.vivachek.protocol.exception.NotSupportProtocolException
import com.vivachek.protocol.process.AbsProcess
import com.vivachek.protocol.process.RealDataProcess
import com.vivachek.protocol.process.StripAddressProcess
import com.vivachek.protocol.process.VerifyCRCProcess
import kotlin.jvm.Throws

/**
 * @Author: YCB
 * @Time: 2022/9/29 16:36:59
 * @Email: congbin.yuan@vivachek.com
 * @Description: 解析蓝牙协议入口/配置类
 */
object Parse {

    private val chain by lazy {
        val verifyCRC = VerifyCRCProcess()
        val strip = StripAddressProcess()
        verifyCRC.next = strip
        strip.next = RealDataProcess()
        verifyCRC
    }
    private val cache = mutableListOf<Int>()

    private var listener:ParseListener?=null

    /**
     * 默认单位为mmol/L
     */
    var unit = UnitEnums.MMOL

    fun setParseListener(listener: ParseListener){
        this@Parse.listener = listener
        var c:AbsProcess? = chain
        while (c!=null){
            c.listener = this@Parse.listener
            c=c.next
        }
    }

    fun removeListener(){
        this@Parse.listener = null
        var c:AbsProcess? = chain
        while (c!=null){
            c.listener = null
            c=c.next
        }
    }

    @Throws(CRCException::class, NotSupportProtocolException::class)
    fun process(data: List<Int>) {
        println(data)
        if (data.first() == START) {
            cache.clear()
        }
        data.forEach {
            cache.add(it)
            if (cache.last() == END) {
                chain.convert(cache.toMutableList(), cache.toMutableList())
                cache.clear()
            }
        }
    }
}